package com.syf.starter.soa.protocol.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class ServerIdleHandler extends IdleStateHandler {
    private String serverName;

    private int maxIdleSends;

    public ServerIdleHandler(String serverName) {
        this(serverName, 360);
    }

    public ServerIdleHandler(String serverName, int maxIdleSends) {
        super(0, 0, maxIdleSends);
        this.serverName = serverName;
        this.maxIdleSends = maxIdleSends;
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        log.warn("服务:[{}] 空闲[{}]秒，没有收到心跳，关闭连接[{}/{}]...", serverName, maxIdleSends, inetSocketAddress.getHostName(), inetSocketAddress.getPort());
        ctx.channel().close();
    }
}
